﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;

namespace EGN_Extractor
{
    public static class EGN
    {
        static readonly int BUFFER_SIZE = 16 + 10;
        static readonly string EGN_PATTERN = @"\b[0-9]{10}\b";

        static void PrintEGNsFromFile()
        {
            string fileName = "persons.txt";
            using (StreamReader reader = new StreamReader(fileName))
            {
                char[] buffer = new char[BUFFER_SIZE];
                Regex regex = new Regex(EGN_PATTERN);
                while (true)
                {
                    int readetChars = reader.ReadBlock(buffer, 10, buffer.Length - 10);
                    if (readetChars == 0)
                    {
                        break;
                    }

                    StringBuilder buff = new StringBuilder();
                    for (int i = 0; i < readetChars + 10; i++)
                    {
                        buff.Append(buffer[i]);
                    }

                    Match match = regex.Match(buff.ToString()); 
                    while (match.Success)
                    {
                        Console.WriteLine(match.Value);
                        match = match.NextMatch();
                    }

                    for (int i = 0; i < 10; i++)
                    {
                        buffer[i] = buffer[buffer.Length - (10 - i)];
                    }
                }
            }
        }

        static string Reverse(Match aMatch)
        {
            string word = aMatch.Value;
            StringBuilder reversedWord = new StringBuilder();
            for (int i = 0; i < word.Length; i++)
            {
                reversedWord.Append(word[word.Length - i - 1]);
            }
            return reversedWord.ToString();
        }

        public static void ReverseEGNs()
        {
            string fileName = "persons.txt";

            string reversedText;
            using (StreamReader reader = new StreamReader(fileName))
            {
                string text = reader.ReadToEnd();
                Regex regex = new Regex(EGN_PATTERN);
                reversedText = regex.Replace(text, new MatchEvaluator(Reverse));
            }

            using (StreamWriter writer = new StreamWriter(fileName))
            {
                writer.Write(reversedText);
            }
        }

        static void Main()
        {
            PrintEGNsFromFile();
            ReverseEGNs();
        }
    }
}
